<?php

namespace app\erp\controller;

use app\admin\model\Synlogs;
use think\Log;

class Bizperson extends Base
{
    public function __construct($starttime, $endtime,$client_id,$client_secret,$account_id,$user_name)
    {
        parent::__construct($client_id, $client_secret,$account_id,$user_name);

        $this->starttime = $starttime;
        $this->endtime   = $endtime;
    }
    public function run($forg_fnumber,$forig_id,$page,$pageSize,$uuid)
    {


        $res = $this->getBizpersonGroupPage($forg_fnumber,$page,$pageSize,$uuid);
        if($res['code'] === 1)
        {
            $response = $this->insertDataAndUpdateSuper($res['data'], $forig_id,$uuid);

            if($response['code'] == 1)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_successnums' => $response['total'],
                    'fk_bdl_status'      => "true",
                    'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
                ]);

                Log::info('业务员同步成功,'. "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forg_fnumber . "参数：" . json_encode($res['data']));

                return "组织编码".$forg_fnumber . ':本次成功同步条数' . $response['total'];
            }
        }elseif ($res['code'] === 2) {
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_successnums' => 0,
                'fk_bdl_status'      => "true",
                'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
            ]);
            return "组织编码".$forg_fnumber . ':本次成功同步条数0';
        }
    }


    private function getBizpersonGroupPage($createorg_number, $pageNo, $pageSize,$uuid)
    {
        $method  = "v2/bdl/bdl_comm_basedata/bdl_bd_bizperson/queryBizperson";

        $fullurl = $this->url . $method;

        Synlogs::where('id',$uuid)->update([
            'fk_bdl_url'        => $fullurl,

        ]);


        $response_data = [
            'data'      => [
                'starttime'             => $this->starttime,
                'endtime'               => $this->endtime,
                'createorg_number'      => $createorg_number,
            ],
            'pageNo'    => $pageNo,
            'pageSize'  => $pageSize,
        ];

        $this->curl->setHeader("Content-Type", "application/json");
        $this->curl->setHeader("accesstoken", $this->getToken());
        $this->curl->setHeader("Idempotency-Key", uuid());

        $res = $this->curl->post($fullurl, json_encode($response_data));

        if ($res && is_object($res) && $res->status == 1)
        {
            if($res->data->totalCount > 0){

                return [
                    'data' => $res->data->rows,
                    'code'  => 1

                ];
            }else{
                return [
                    'code'  => 2,
                ];
            }

        }else{
            if(strlen($res->message) > 255)
            {
//                $res->message = substr($res->message,0,155);

                return $this->error( 'aaaaaaaa'  . request()->action() . $res->message);

            }
            if(property_exists($res,'errorCode') && $res->errorCode == 404)
            {
                return $this->error( 'aaaaaaaa'  . request()->action() . $res->message);
            }
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_exceptionmsg'   => $res->message,
                'fk_bdl_status'         => "false",
            ]);

            Log::info('业务员同步失败,'  . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $createorg_number . "参数：" . json_encode($response_data));
            return [
                'data' => false,
                'code'  => 0
            ];
        }


    }

    private function insertDataAndUpdateSuper($data, $forgid,$uuid)
    {
        $count = 0;
        if(!empty($data))
        {

            try {
                // 组装 data 并插入
                foreach ($data as $k => $v)
                {

                    //判断是否已经存在
                    $isExist = \app\admin\model\Bizperson::where('fnumber', $v->number)->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

                    //组装
                    $insertData = [
                        'fname'                             => $v->name,
                        'fnumber'                           => $v->number,
                        'fenable'                           => $v->enable,
                        'forgid'                            => $forgid,
                        'fk_bdl_bizpersontype'              => $v->bdl_bizpersontype,
                        'fk_bdl_comment'                    => $v->group_number,
                        'fk_bdl_createtime'                 => $v->createtime,
                        'fk_bdl_modifytime'                 => $v->modifytime,
                        'fk_bdl_bd_datacenter'              => $this->account_id,
                    ];

                    property_exists($v,'bdl_issystem')                    ?   $insertData['fk_bdl_issystem']    =       $v->bdl_issystem :               '';
                    property_exists($v,'bdl_user_phone')                    ?   $insertData['fk_bdl_phone']    =       !empty($v->bdl_user_phone) ? $v->bdl_user_phone : ' ' :               ' ';

                    if(!empty($isExist))
                    {
                        unset($insertData['forgid']);
                        unset($insertData['fk_bdl_bd_datacenter']);

                        \app\admin\model\Bizperson::where('id',$isExist['id'])->update($insertData);
                    }else{
                        \app\admin\model\Bizperson::create($insertData);

                    }

                    $count++;
                }

                // 插入成功后 更新
                $this->updateBizoersonCategory($forgid);
            }catch (\Exception $e)
            {

                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_exceptionmsg' => $e->getMessage(),
                    'fk_bdl_status'         => "false",
                ]);
                Log::error('业务员同步失败,'.$e->getMessage(). "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forgid . "参数：" . json_encode($data));

                $this->error( 'aaaaaaaa'  . request()->action() . $e->getMessage());
            }
        }

        return [
            'code'      =>1,
            'total'     => $count,
        ];

    }

    public function updateBizoersonCategory($forgid)
    {
        $data = \app\admin\model\Bizperson::where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->select();

        foreach ($data as $k=>$v)
        {
            $super = \app\admin\model\Bizpersoncate::where('fnumber',$v['fk_bdl_comment'])->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

            if($super)
            {
                \app\admin\model\Bizperson::where('id', $v['id'])->update(['fk_bdl_bdgroup' => $super['id']]);
            }
        }
    }


}